import { CommonModal } from "@/pages/OrderModule/common/components/CommonModal";
import { Form, Modal, message, Select, Tooltip, Button, Input, Alert } from "antd";
import { find, isEmpty } from "lodash";
import OrderNumberCount from "../../components/OrderNumberCount";
import Api from "../../service";
import CommonLoading from "@/components/CommonLoading";
import { useState, useEffect, useRef, useMemo } from "react";
import OrderAreaRadioGroup from "../../components/OrderAreaRadioGroup1";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { getAllPrinter, checkComponentsIsOpen } from "@/utils/print.jsx";
import { loadScript, isJSON } from "@/utils/utils.jsx";
import { setPrinterName, getPrinterName, getCurrentUser } from "@/utils/authority";
import CommonSelect from "@/pages/OrderModule/common/components/CommonSelect";
import styles from "./index.module.less";
import { EditOutlined } from "@ant-design/icons";
import IframeEditModal from "./IframeEditModal";
import Typography from "@/pages/OrderModule/common/components/Typography";


const { Option } = Select;

const printQueenArr = [];

/** 获取运单号 */
function DeliveryPrint(props) {
	const [showNumber, setShowNumber] = useState({});
	const [loading, setLoading] = useState(false);
	const filterIds = useRef(undefined);
	const [labelList, setLabelList] = useState([]); //标签模板下拉
	const [printList, setPrintList] = useState([]); //打印机列表
	const [printData, setPrintData] = useState({}); //获取打印数据
	const [templateId, setTemplateId] = useState(""); //选择当前的发货单id
	const [kuaimaiItem, setKuaimaiItem] = useState({}); //编辑当前的快麦模板
	const [showTemplateEdit, setShowTemplateEdit] = useState(false); //展示模版编辑页面

	const { searchForm, selectKeys, orderList, handleCancel, handleOk } = props;

	const [form] = Form.useForm();

	const commonParams = useMemo(() => {
		return {
			el: "#kuaimaiiframeviewDelivery",
			appId: "1666316938957",
			itemsId: "400",
			libraryType: "2",
			userId: getCurrentUser()?.id + ""
		};
	}, []);

	useEffect(() => {
		if (window.KM_Template) {
			window.KMTEMPLATE = new KM_Template();
		} else {
			loadScript("https://label-open.kuaimai.com/sdk/KM_Template.umd.js").then(() => {
				window.KMTEMPLATE = new KM_Template();
			});
		}
		getLabelList();
		getAllPrinter(value => {
			const printname = getPrinterName();
			if (printname && value.includes(printname)) {
				form.setFieldsValue({
					printer: printname
				});
			}
			setPrintList(value);
		});
		const kmTemplateId = localStorage.getItem("kmTemplateId");
		if (kmTemplateId && !isNaN(kmTemplateId)) {
			form.setFieldsValue({
				tempalteId: kmTemplateId + ""
			});
			setTemplateId(Number(kmTemplateId));
		}
	}, []);

	useEffect(() => {
		if (filterIds.current.length) {
			getInvoicePrintData();
		}
	}, [filterIds.current, searchForm]);

	//获取打印数据
	const getInvoicePrintData = async () => {
		setLoading(true);
		let res;
		res = await Api.queryInvoicePrintData({
			orderIds: filterIds.current,
			sortBy: searchForm.sortBy,
			sortType: searchForm.sortType
		});
		const { success, data = [] } = res || {};
		if (success) {
			setPrintData(data);
		}
		setLoading(false);
	};

	//获取标签模板
	const getLabelList = async () => {
		setLoading(true);
		let res;
		res = await Api.queryLabelTemplateList({
			labelType: 8
		});
		const { success, data = [] } = res || {};
		if (success) {
			setLabelList(data);
		}
		setLoading(false);
	};

	//更新發貨單打印狀態
	const handleUpdateShippingNotePrintState = async () => {
		setLoading(true);
		let res;
		res = await Api.updateShippingNotePrintState(filterIds.current);
		const { success, data = [] } = res || {};
		if (success) {
			handleOk();
		}
		setLoading(false);
	};

	const onOk = () => {
		form
			.validateFields()
			.then(val => {
				if (isJSON(printData)) {
					printQueenArr.push(...JSON.parse(printData));
				}
				if (printQueenArr.length) {
					handleprint(val);
				} else {
					message.info("打印数据为空");
				}
			})
			.catch(err => { });
	};

	//打印执行逻辑
	const handleprint = val => {
		const obj = printQueenArr.shift();
		if (!obj) {
			message.success("打印完成");
			handleUpdateShippingNotePrintState();
			return;
		}
		setLoading(true);
		const { tempalteId, printer } = val;
		return new Promise(() => {
			const parms = {
				...commonParams,
				id: Number(tempalteId),
				data: obj,
				usbList: [printer],
				callback: () => {
					handleprint(val);
				}
			};
			KMTEMPLATE.printLabelNoPreview(parms);
		});
	};

	//点击选择模板
	const handleSelectTemplate = e => {
		const item = find(labelList, ["kmTemplateCode", e]);
		setKuaimaiItem(item);
		localStorage.setItem("kmTemplateId", Number(e));
		setTemplateId(Number(e));
	};

	//处理返回的数据
	const handleDealData = arr => {
		const list = [];
		var obj = {};
		for (var i = 0; i < arr.length; i++) {
			obj[arr[i].key] = arr[i].name;
		}
		list.push(obj);
		return list;
	};

	//预览模板
	const handleView = async () => {
		if (templateId) {
			const { data = {}, success } = await Api.queryFieldManageList();
			if (success) {
				// const obj = {};
				// obj.zjf_order_label = handleDealData(data?.orderInfoList);
				// obj.zjf_purchase_label = handleDealData(data?.purchaseInfoList);
				// obj.zjf_library_label = handleDealData(data?.libraryInfoList);
				// obj.zjf_other_label = handleDealData(data?.otherInfoList);
				// obj.zjf_field_attribute_label = handleDealData(data?.goodsInfoList);
				// obj.订单信息 = handleDealData(data?.orderInfoList);
				// obj.采购单信息 = handleDealData(data?.purchaseInfoList);
				// obj.入库信息 = handleDealData(data?.libraryInfoList);
				// obj.其他信息 = handleDealData(data?.otherInfoList);
				// obj.商品信息 = handleDealData(data?.goodsInfoList);
				printQueenArr.push(...JSON.parse(printData));
				const obj = printQueenArr.shift();

				KMTEMPLATE.printLabel({
					...commonParams,
					id: templateId,
					data: obj
				});
			}
		} else {
			message.info("请选择发货单模板");
		}
	};

	// 设置打印机名称
	const handlePrinterName = name => {
		setPrinterName(name);
	};

	//底部按钮渲染
	const footerRender = () => {
		return (
			<div>
				<Button style={{ marginRight: "16px" }} onClick={() => handleCancel()}>
					取消
				</Button>
				<Button style={{ marginRight: "16px" }} onClick={() => handleView()}>
					预览
				</Button>
				<Button
					onClick={() => {
						onOk();
					}}
					type="primary"
				>
					确认
				</Button>
			</div>
		);
	};

	const orderAreaRadioProps = {
		searchForm,
		selectKeys,
		orderList,
		states: [20],
		updateShowNumer(obj, ids) {
			filterIds.current = ids;
			setShowNumber(obj);
		},
		title: "待发货订单"
	};

	//标签模板
	const options =
		!isEmpty(labelList) &&
		labelList.map(d => (
			<Option value={d.kmTemplateCode} key={d.id} label={d.templateName}>
				<Tooltip title={`${d.templateName} ${d.sizeWidth}*${d.sizeHeight}`}>{d.templateName} {d.sizeWidth}*{d.sizeHeight}</Tooltip>
			</Option>
		));

	//打印列表
	const printOptions = useMemo(() => {
		if (printList?.length) {
			return printList.map(d => (
				<Option key={d} value={d}>
					{d}
				</Option>
			));
		}
	}, [printList]);

	//模板编辑页面
	const IframeEditModalProps = {
		templateId,
		kuaimaiItem,
		commonParams,
		handleOk() {
			setShowTemplateEdit(false);
		},
		handleCancel() {
			setShowTemplateEdit(false);
		}
	};

	return (
		<>
			{showTemplateEdit && <IframeEditModal {...IframeEditModalProps} />}
			<div id="kuaimaiiframeviewDelivery" style={{ flex: 1 }}></div>
			<CommonModal
				footer={footerRender()}
				title={{ title: `打印发货单` }}
				open={true}
				width="530px"
				onOk={onOk}
				onCancel={handleCancel}
			>
				<Alert
					style={{ marginBottom: 16 }}
					showIcon
					message={<Typography as="s1">代发订单、无快递的订单都支持打印</Typography>}
				/>
				<OrderAreaRadioGroup wrapStyle={{ marginTop: 16 }} {...orderAreaRadioProps} />
				<div style={{ marginTop: "16px" }}>
					<OrderNumberCount data={[{ label: "待发货", value: showNumber[20] }]} />
				</div>
				<div style={{ marginTop: "16px", marginBottom: "16px" }}>
					<SubTitle title={"打印发货单"} as="s2" symbol />
				</div>
				<Form form={form} name="delivery-print-modal">
					<Form.Item noStyle>
						<Input.Group compact>
							<Form.Item
								label="发货单模板"
								style={{
									width: "calc(100% - 24px)"
								}}
								rules={[{ required: true, message: "请选择发货单" }]}
								name="tempalteId"
							>
								<Select
									style={
										{
											// width: "calc(100% - 24px)"
										}
									}
									aria-required
									onChange={e => handleSelectTemplate(e)}
									placeholder="发货单模板"
									allowClear
								>
									{options}
								</Select>
							</Form.Item>

							<Button
								onClick={() => {
									if (templateId) {
										setShowTemplateEdit(true);
									} else {
										message.info("请选择发货单模板");
									}
								}}
								icon={<EditOutlined />}
							/>
						</Input.Group>
					</Form.Item>
					<Form.Item label="打印机" rules={[{ required: true, message: "请选择发货单" }]} name="printer">
						<Select onChange={handlePrinterName} placeholder="打印机" allowClear>
							{printOptions}
						</Select>
					</Form.Item>
				</Form>
				<CommonLoading loading={loading} />
			</CommonModal>
		</>
	);
}

export default DeliveryPrint;
